package com.example.stlink.configs.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.stlink.R;
import com.example.stlink.fragments.StuHomeFragment;
import com.example.stlink.model.constants.ModelFieldConstants;
import com.example.stlink.model.constants.UrlConstants;
import com.example.stlink.model.domain.Course;
import com.example.stlink.model.response.BaseResponse;
import com.example.stlink.utils.httpUtils.PostBodyParamHttpUtils;

import java.util.List;

/**
 * 用于将课程数据渲染进ListView控件中进行显示
 */
public class StuAddCourseAdapter extends RecyclerView.Adapter<StuAddCourseAdapter.ViewHolder> implements View.OnClickListener  {

    private com.example.stlink.configs.onRecyclerViewItemClickListener  onRecyclerViewItemClickListener;
    private RecyclerView rvParent;

    private final List<Course> mCourseData;

    private final Context mContext;
    private final int resourceId;
    private int role;

    private Handler handler;

    public StuAddCourseAdapter(@NonNull Context context, int resourceId, @NonNull List<Course> data, int role) {
        this.mContext = context;
        this.mCourseData = data;
        this.resourceId = resourceId;
        this.role = role;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //指定一个父控件
        rvParent = (RecyclerView) parent;

        View view = LayoutInflater.from(mContext)
                .inflate(resourceId, parent, false);
        ViewHolder holder = new ViewHolder(view);
        view.setOnClickListener(this);

        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Course course = mCourseData.get(position);
        Glide.with(mContext).load(course.getmCoursePhoto()).into(holder.ivCoursePhoto);
        holder.tvCourseName.setText(course.getmCourseName());
        holder.tvCollegeName.setText(course.getmCollegeName());
        setAddClickListener(holder, position);
    }

    @Override
    public int getItemCount() {
        return mCourseData.size();
    }

    //重载点击事件，指定点击事件时执行自定义的onItemClick
    @Override
    public void onClick(View view) {
        int position = rvParent.getChildAdapterPosition(view);
        if (onRecyclerViewItemClickListener != null){
            onRecyclerViewItemClickListener.onItemClick(rvParent, view, position);
        }
    }


    //实例化自定义接口
    public void setOnItemClickListener(com.example.stlink.configs.onRecyclerViewItemClickListener onRecyclerViewItemClickListener) {
        this.onRecyclerViewItemClickListener = onRecyclerViewItemClickListener;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivCoursePhoto;
        TextView tvCourseName;
        TextView tvCollegeName;
        ImageView ivRight;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            ivCoursePhoto = itemView.findViewById(R.id.iv_course_photo);
            tvCourseName = itemView.findViewById(R.id.tv_course_name);
            tvCollegeName = itemView.findViewById(R.id.tv_college_name);
            ivRight = itemView.findViewById(R.id.cv_right);
        }
    }

    /**
     * 添加删除事件，云端删除成功后，子线程个主线程发送信息，请求课程列表进行刷新
     * @param holder 当前card的相关数据
     * @param position 位置
     */
    public void setAddClickListener(ViewHolder holder, int position){
        holder.ivRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //添加取消
                AlertDialog alertDialog2 = new AlertDialog.Builder(mContext)
                    .setMessage("确认加入课程")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            deleteCourse(position);
                            handler = new Handler(Looper.getMainLooper()){
                                @Override
                                public void handleMessage(@NonNull Message msg) {
                                    super.handleMessage(msg);
                                    Toast.makeText(mContext, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                                    if(msg.arg1 == 200){
                                        Toast.makeText(mContext, "添加成功", Toast.LENGTH_SHORT).show();
                                        AppCompatActivity appCompatActivity = (AppCompatActivity) mContext;
                                        appCompatActivity.finish();
                                        //刷新数据
                                        StuHomeFragment.refreshData();
                                    }
                                }
                            };
                        }
                    })
                    .setNegativeButton("取消", (dialogInterface, i) -> { })
                    .create();
                alertDialog2.show();
            }
        });
    }

    /**
     * 更新信息网络请求
     */
    private void deleteCourse(int position){
        new Thread(() -> {
            AppCompatActivity appCompatActivity = (AppCompatActivity) mContext;
            Bundle bundle = appCompatActivity.getIntent().getExtras();
            Long courseId = mCourseData.get(position).getmCourseId();
            long userId = bundle.getLong(ModelFieldConstants.ID);
            String urlParam = ModelFieldConstants.COURSE_ID + "=" + courseId + "&" +
                        ModelFieldConstants.USER_ID + "=" + userId;
            String url = UrlConstants.STUDENT_SELECT + "?" + urlParam;

            new PostBodyParamHttpUtils() {
                @Override
                public void nextMethod(BaseResponse<Object> baseResponse) {
                    Message message = new Message();
                    message.obj = "添加成功";
                    message.arg1 = 200;
                    handler.sendMessage(message);
                }
                @Override
                public void failedMethod(BaseResponse<Object> baseResponse) {
                    Message message = new Message();
                    System.out.println("添加失败.......................");
                    message.obj = "添加失败";
                    message.arg1 = 400;
                    handler.sendMessage(message);
                }
            }.postConnect(url, "");
        }).start();
    }
}
